package com.yxf.variousshapes.shapes;

import android.graphics.Color;

import com.yxf.variousshapes.Point;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import static android.opengl.GLES20.GL_FLOAT;
import static android.opengl.GLES20.GL_TRIANGLE_STRIP;
import static android.opengl.GLES20.glDrawArrays;
import static android.opengl.GLES20.glVertexAttribPointer;

public class Ring extends Shape {
    private static final int EDGE_COUNT = 180;
    private static final int POINT_COUNT = (EDGE_COUNT + 1) * 2;

    private final float radius;
    private final float width;

    private final int insideColor = Color.YELLOW;
    private final int outsideColor = Color.MAGENTA;

    private float[] vertices;
    private FloatBuffer vertexData;


    public Ring(Point center, float radius, float width) {
        super(center, radius * 2, radius * 2);
        this.radius = radius;
        this.width = width;

        vertices = new float[(POSITION_COMPONENT_COUNT + COLOR_COMPONENT_COUNT) * POINT_COUNT];
        int i = 0;
        while (i < vertices.length) {
            int index = i / (POSITION_COMPONENT_COUNT + COLOR_COMPONENT_COUNT);
            double angle = Math.PI  * index / EDGE_COUNT;
            if (index % 2 == 0) {
                vertices[i++] = center.x + (float) Math.cos(angle) * (radius - width);
                vertices[i++] = center.y + (float) Math.sin(angle) * (radius - width);
                vertices[i++] = Color.red(insideColor) / 255f;
                vertices[i++] = Color.green(insideColor) / 255f;
                vertices[i++] = Color.blue(insideColor) / 255f;
            } else {
                vertices[i++] = center.x + (float) Math.cos(angle) * (radius);
                vertices[i++] = center.y + (float) Math.sin(angle) * (radius);
                vertices[i++] = Color.red(outsideColor) / 255f;
                vertices[i++] = Color.green(outsideColor) / 255f;
                vertices[i++] = Color.blue(outsideColor) / 255f;
            }
            vertexData = ByteBuffer.allocateDirect(vertices.length * BYTES_PER_FLOAT)
                    .order(ByteOrder.nativeOrder())
                    .asFloatBuffer();
            vertexData.put(vertices);
        }
    }

    @Override
    public void draw() {
        vertexData.position(0);
        glVertexAttribPointer(aPositionLocation, POSITION_COMPONENT_COUNT, GL_FLOAT,
                false, STRIDE, vertexData);
        vertexData.position(POSITION_COMPONENT_COUNT);
        glVertexAttribPointer(aColorLocation, COLOR_COMPONENT_COUNT, GL_FLOAT,
                false, STRIDE, vertexData);

        glDrawArrays(GL_TRIANGLE_STRIP, 0, POINT_COUNT);
    }
}
